package com.dearbinge.pay.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.dearbinge.data.api.orderTable.OrderTableService;
import com.dearbinge.data.api.rocket.RocketService;
import com.dearbinge.data.pojo.orderTable.OrderTable;
import com.dearbinge.data.pojo.rocket.Rocket;
import com.dearbinge.pay.util.WxpayUtil;
import com.dearbinge.utils.Constants;
import com.dearbinge.utils.MD5s;
import com.dearbinge.utils.ResultMsg;

/**
 *
 * @author aiche
 *微信支付
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/WechatPay")
@EnableAutoConfiguration
public class WechatPay {

	@Autowired
	private RocketService rocketService;

	@Autowired
	private OrderTableService orderTableService;
	/**
	 * 统一下单
	 * @param totalFee 总金额
	 * type 1火箭支付    2商城订单支付
	 * @return
	 */
	@ApiOperation(value = "根据条件分页查询", notes = "根据条件分页查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "totalFee", value = "订单成交价格（以分为单位）",paramType = "query"),
			@ApiImplicitParam(name = "type", value = "1火箭支付    2商城订单支付",paramType = "query"),
			@ApiImplicitParam(name = "wechatNumber", value = "微信订单编号",paramType = "query")
	})
	@RequestMapping(value = "/unifiedorder", method = RequestMethod.GET)
	public  ResultMsg<SortedMap<String, String>> unifiedorder(String totalFee,String userId,String type,String wechatNumber) {
		SortedMap<String, String> map2 = new TreeMap<String, String>();
		try {

			long timeMillis = System.currentTimeMillis();
			int i1 = (int) ((Math.random() * 9 + 1) * 100000);
			String orderNo = timeMillis+""+i1;

			//统一下单
			SortedMap<String, String> map = new TreeMap<String, String>();
			map.put("appid", Constants.appid);// 应用ID
			map.put("mch_id", Constants.mch_id);// 商户号
			map.put("nonce_str", WxpayUtil.genNonceStr());// 随机字符串
			if(type.equals("1")){
				map.put("out_trade_no", orderNo);// 商户订单号
				map.put("body", "UWE购火箭充值");// 商品描述
			}else{
				map.put("out_trade_no", wechatNumber);// 商户订单号
				map.put("body", "UWE购");// 商品描述
				//校验价钱对不对
				BigDecimal selectTotalMonryByWechatNumber = orderTableService.selectTotalMonryByWechatNumber(wechatNumber).setScale(2, BigDecimal.ROUND_UP);
				if( 0 != new BigDecimal("wechatNumber").compareTo(selectTotalMonryByWechatNumber )){
					throw new Exception("用户购买修改单了订单价格，微信下单统一编号是 ===="+wechatNumber);
				}
			}

			map.put("total_fee", totalFee);// 总金额
			map.put("spbill_create_ip", "192.168.1.1");// 终端IP
			map.put("notify_url", "https://www.so.com");// 通知地址
			map.put("trade_type", "APP");// 交易类型
			String createSign2 = WxpayUtil.createSign(map);
			String perPayId = WxpayUtil.getPerPayId(map);


			//封装微信支付参数
			map2.put("appid", Constants.appid);// 应用ID
			map2.put("partnerid", Constants.mch_id);// 商户号
			map2.put("noncestr", WxpayUtil.genNonceStr());// 随机字符串
			map2.put("prepayid",perPayId);// 微信返回的支付交易会话ID
			map2.put("package","Sign=WXPay");// 扩展字段
			map2.put("timestamp",WxpayUtil.getTimestamp());// 时间戳
			String createSign = WxpayUtil.createSign(map2);
			map2.put("sign",createSign);// 签名

			//查询订单专用
			if(type.equals("1")){
				map2.put("outTradeNo", orderNo);
			}else{
				map2.put("outTradeNo", wechatNumber);
			}


			//生成火箭订单
			if(type.equals("1")){
				OrderTable orderTable = new OrderTable();
				orderTable.setUserId(userId);
				orderTable.setNumber(orderNo);
				orderTable.setBusinessType("0");
				orderTable.setPreferentialPrice(new BigDecimal(totalFee));
				orderTable.setOrderStatus(0);
				orderTable.setIsDistribution(0);
				orderTable.setAssessType(0);
				orderTable.setShopId("admin");
				orderTable.setCreateBy(userId);
				Integer dataCode = orderTableService.insert(orderTable);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500,  "error");
		}
		return ResultMsg.ok(map2);
	}

	/**
	 * 查询订单
	 * @param outTradeNo 订单号
	 * @param fee 钱
	 * @param userId 用户id
	 * @return
	 */
	@ApiImplicitParams({
		@ApiImplicitParam(name = "outTradeNo", value = "编号",paramType = "query"),
		@ApiImplicitParam(name = "type", value = "1火箭支付    2商城订单支付",paramType = "query"),
		@ApiImplicitParam(name = "fee", value = "金额",paramType = "query"),
		@ApiImplicitParam(name = "userId", value = "用户id",paramType = "query")
	})
	@RequestMapping(value = "/orderquery", method = RequestMethod.GET)
	public ResultMsg<Boolean> orderquery(String transactionId, String outTradeNo, int fee,String userId,String type) {
		Boolean boolean1;
		try {
			boolean1 = true;
			boolean1 = WxpayUtil.verifyOrder(transactionId,outTradeNo,Double.valueOf(fee));
			if(boolean1){
				if(type.equals("1")){
					//增加火箭次数
					Rocket rocket = new Rocket();
					rocket.setUserId(userId);
					rocket.setRocketType(0);
					rocket.setRocketNumber( (new Double((fee/6)/100)).intValue());
					rocketService.recharge(rocket);
					//修改订单状态
					System.out.println("outTradeNo=="+outTradeNo);
					orderTableService.updateStatus(outTradeNo, 1);
				}else{
					orderTableService.updateStatusByWechatNumber(outTradeNo, 1);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			boolean1 = false;
		}
		return ResultMsg.ok(boolean1);
	}




	public static String createSign(String characterEncoding,
			SortedMap<String, String> parameters) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + Constants.key);
		String sign = MD5s.MD5Encode(sb.toString(), characterEncoding)
				.toUpperCase();
		System.out.println("签名：" + sign);
		return sign;
	}

}
